
import Jwt from "../../prototype/jwt";
import admin_role from "../../models/admin_role";
class Role_management extends Jwt{
  constructor() {
    super();
    this.get_list = this.get_list.bind(this);
    this.do_delete = this.do_delete.bind(this);
    this.do_edit = this.do_edit.bind(this);
  }

  /**
   * 获取用户列表
   * pageNo: 1,  pageSize: 10,  username: '',
   * @param req
   * @param res
   * @returns {Promise<void>}
   */
  async get_list(req, res) {
    const body = {
      status: 200,
      msg: '请求成功'
    }

    const { pageNo, pageSize, permission} = req.body;

    try {
      if([pageNo, pageSize].includes(undefined)) {
        throw ('参数错误')
      }
      const query = permission ? {admin_role: permission} : {}
      const list = await admin_role.find(query).skip((req.body.pageNo - 1) * req.body.pageSize).limit(req.body.pageSize);
      body.totalCount = admin_role.length;
      body.data = list || [];
    } catch (e) {
      body.status = 201
      body.msg = e.toString();
    }

    res.send(body)
  }

  async do_edit(req, res) {
    const body = {
      status: 200,
      msg: '请求成功'
    }
    const {_id, permission} = req.body;
    try {
      if(!permission) throw ('参数错误')
      if(!_id) {
        body.data = await admin_role.create({permission: permission})
      } else {
        body.data = await admin_role.updateOne({_id}, { permission})
      }
    } catch (e) {
      body.msg = e.toString()
      body.status = 201
    }

    res.send(body)
  }

  async do_delete(req, res) {
    const body = {
      status: 200,
      msg: '请求成功'
    }
    const {ids} = req.body;
    try {
      if(!ids) throw ('参数错误')
      ids.split(',').map(async el => {
        await admin_role.deleteOne({_id: el})
      })
    } catch (e) {
      body.msg = e.toString()
      body.status = 201
    }

    res.send(body)
  }
}

export default Role_management;
